/*
* Copyright (C), 2015-2017, 苏宁消费金融公司
* Author:   16060223
* Date:     2017/7/6 19:21
* Description: //模块目的、功能描述      
* History: //修改记录
* 修改人姓名             修改时间            版本号                  描述
*/
package com.mobileClientKernel.android.commonLayer;


import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.mobileClientKernel.android.commonLayer.DESUtil;
import com.mobileClientKernel.android.commonLayer.MD5Util;

public class SecurityStorageUtil {
    private static String key;

    private static SharedPreferences mSharedPreferences;

    private static synchronized SharedPreferences getPreferneces(Context mContext) {
        if (mSharedPreferences == null) {

            mSharedPreferences = mContext.getSharedPreferences("jjconfig", Context.MODE_PRIVATE);
            String dev = UniqueIDUtil.getDeviceId(mContext.getApplicationContext());
            JJLog._d("SecurityStorageUtil"," getPreferneces dev = "+dev);
            dev = MD5Util.getMD5Code(dev);
            JJLog._d("SecurityStorageUtil"," getPreferneces  md5 dev = "+dev);
            key = "";
            if (dev.length() == 8) {
                key = dev;
            } else {
                key = dev.substring(0, 8);
            }
            JJLog._d("SecurityStorageUtil"," getPreferneces  key = "+key);
        }
        return mSharedPreferences;
    }

    public static void putString(String key, String value,Context mContext){
        getPreferneces(mContext).edit().putString(key, encryptString(value)).commit();
    }

    public static void removeString(String key,Context mContext){
//        try {
//            getSecurityStorage().removeString(key);
//        } catch (JAQException e) {
//            JJLog.e("SecurityStorageUtil [remove] ErrorCode = "+e.getErrorCode());
//        }
        getPreferneces(mContext).edit().remove(key).commit();
    }

    public static String getString(String key,Context mContext){
        String s = null;
        s = getPreferneces(mContext).getString(key,"");
        if(!TextUtils.isEmpty(s)){
            s = decryptString(s);
        }
        return s;
    }

    private static String encryptString(String data){
        try {
            data = DESUtil.encryptDES(data, key);
            JJLog.d("SecurityStorageUtil encryptString data = "+data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    private static String decryptString(String data){
        try {
            data = DESUtil.decryptDES(data, key);
            JJLog.d("SecurityStorageUtil decryptString data = "+data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }
}
